package com.bawei.module_mine.ui.login

import com.bawei.module_mine.http.MineApi
import com.bawei.module_mine.http.MineNetModule
import com.bawei.module_mine.model.LoginMode
import com.bawei.module_mine.model.LoginPostModel
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import javax.inject.Inject

/**
 *作者：lxy
 *功能:
 *时间：2025/5/26
 */
class LoginRepository @Inject constructor() {

    @Inject
    @MineNetModule.CommonMineApi
    lateinit var mineApi: MineApi

    fun sendLoginCode(operatorType: String, phone: String) = flow {
        emit(mineApi.sendLoginCode(operatorType, phone))
    }.flowOn(Dispatchers.IO)

    fun sendForgetPwdCode(operatorType: String, phone: String) = flow {
        emit(mineApi.sendForgetPwdCode(operatorType, phone))
    }.flowOn(Dispatchers.IO)

    fun login(
        mode: LoginMode,
        phone: String = "",
        password: String = "",
        smsCode: String = ""
    ) = flow {
        val postModel = LoginPostModel(phone, password, mode.value, smsCode)
        val body = RequestBody.create(
            "application/json;charset=utf-8".toMediaTypeOrNull(),
            com.bawei.lib_storage.mmkv.utils.Gson.toJson(postModel)
        )
        emit(mineApi.login(body))
    }.flowOn(Dispatchers.IO)
}